﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Gman.Entity.Entities;
using Gman.WebApp.ServiceControllers;
using Gman.WebApp.Models;
using System.Web.Caching;
using Gman.WebApp.Controllers.Base;
using Gman.WebApp.OperacionServiceRef;

namespace Gman.WebApp.Controllers
{
    public class ProveedorController : BaseController
    {
         
        private OperacionServiceController service = new OperacionServiceController();

        private GeneralServiceController generalService = new GeneralServiceController();

        //
        // GET: /Provedor/

        public ActionResult Index()
        {

            ProveedorBE proveedor = new ProveedorBE();
            UbigeoBE ubigeo = new UbigeoBE();
            var model = new ProveedorModel(ListaProveedor());


            return View(model);
        }

        private IList<ProveedorBE> ListaProveedor()
        {

            //UsuariosBE user = (UsuariosBE)Session["user"];
            ProveedorBE bean = new ProveedorBE();
            //sede.IDEmp = user.IDEmp;

            IList<ProveedorBE> lista = new List<ProveedorBE>();
            lista = service.ListProveedor(bean);
            return lista;
        }



        //private IList<PersonalBE> ListaPersonal(int idpro)
        //{

        //    UsuariosBE user = (UsuariosBE)Session["user"];
        //    PersonalBE pers = new PersonalBE();
        //    pers.IDEmp = user.IDEmp;
        //    pers.IDOrigen = idpro;//Int64.Parse(TempData["IDSede"] .ToString());
        //    pers.OrigenPers = 2;
        //    IList<PersonalBE> lista = new List<PersonalBE>();
        //    lista = service.ListarPersonal(pers);
        //    return lista;
        //}

        //
        // GET: /Provedor/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /Provedor/Create

        public ActionResult Search()
        {


            var model = modelProveedor();
            var cache = new CacheProvider();
            cache.Set(model.ID.Value.ToString(), model);

            model.Action = "search";
            //return View(model);

            return View(@"~/Views/Proveedor/Edit.aspx", model);
            //return View();
        }

        public JsonResult UpdateForm(string sortBy)
        {
            string result = "Your result here";
            return Json(result);
        }





        //
        // POST: /Provedor/Create

        //FormCollectionProveedorBE proveedor
        //[HttpPost]
        public JsonResult Save(Guid id, string action)
        //public ActionResult Create(FormCollection collection)
        {
            try
            {
                UsuariosBE user = (UsuariosBE)Session["user"];
                ProveedorModel model = GetProveedorModel(id);

                List<PersonalBE> ListPer = new List<PersonalBE>();
                foreach (var personal in model.Personales)
                {

                    personal.Personal.UsuReg = user.NomUsu;
                    personal.Personal.TermCnxMod = Environment.MachineName;
                    personal.Personal.IDEmp = user.IDEmp;
                    ListPer.Add(personal.Personal);
                }

                if (model.Action == "create")
                {

                    ProveedorBE proveedor = new ProveedorBE();

                    proveedor = model.proveedor;
                    proveedor.TermCnxReg = Environment.MachineName;

                    proveedor.CodUbigeo = model.Ubigeo.CodDpto + model.Ubigeo.CodProv + model.Ubigeo.CodDist;



                    int codprov = service.Registrarproveedor(proveedor, ListPer);

                    if (codprov >= 1)
                    {
                        TempData["codprov"] = codprov;
                        return AjaxResultSuccess(string.Format("Proveedor {0} se guardo exitosamente.", codprov));



                    }
                    else
                    {
                        return AjaxResultSuccess(string.Format("No se guardo exitosamente."));
                    }


                }
                if (model.Action == "edit")
                {
                    ProveedorBE proveedor = new ProveedorBE();

                    proveedor = model.proveedor;
                    proveedor.TermCnxReg = Environment.MachineName;

                    proveedor.CodUbigeo = model.Ubigeo.CodDpto + model.Ubigeo.CodProv + model.Ubigeo.CodDist;

                    int codprov = service.Actualizarproveedor(proveedor, ListPer, model.toDelete);

                    if (codprov >= 1)
                    {
                        TempData["codprov"] = codprov;
                        return AjaxResultSuccess(string.Format("Proveedor {0} se guardo exitosamente."));



                    }
                    else
                    {
                        return AjaxResultSuccess(string.Format("No se guardo exitosamente."));
                    }

                }




                return AjaxResultSuccessNoParam();
                //return View();


            }
            catch (Exception ex)
            {
                return AjaxResultError(ex.Message);
            }
        }

        //
        // GET: /Provedor/Edit/5



        public ActionResult Create()
        {


            var model = modelProveedor();

            var cache = new CacheProvider();
            cache.Set(model.ID.Value.ToString(), model);

            model.Action = "create";

            return View(@"~/Views/proveedor/Edit.aspx", model);

        }


        ProveedorModel modelProveedor()
        {

            ProveedorBE proveedor = new ProveedorBE();
            UbigeoBE ubigeo = new UbigeoBE();

            //var model = new ProveedorModel(proveedor, ubigeo, ListaProveedor());

            var model = new ProveedorModel(proveedor, ubigeo, ListaProveedor(), new PersonalBE());
            model.ToolBar = new ToolBarModel();



            model.Departamento = new SelectList(generalService.ListarUbigeo(new UbigeoBE(), 1), "CodDpto", "DescUbigeo", model.Departamento);
            model.Provincia = new SelectList(generalService.ListarUbigeo(new UbigeoBE(), 4), "CodProv", "DescUbigeo", model.Provincia);
            model.Distrito = new SelectList(generalService.ListarUbigeo(new UbigeoBE(), 4), "CodDist", "DescUbigeo", model.Provincia);


            return model;
        }


        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /Provedor/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }



        public JsonResult Prvncias_SelectedDprt(string Sel_Dpto)
        {
            UbigeoBE ubi = new UbigeoBE();
            ubi.CodDpto = Sel_Dpto;

            JsonResult result = new JsonResult();
            var vPrvncias = generalService.ListarUbigeo(ubi, 2);



            result.Data = vPrvncias.ToList();
            result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;

            //create1(ubi);
            return result;

        }

        public JsonResult Dictritos_SelectedProv(string Sel_Prov, string Sel_Dpto)
        {
            UbigeoBE ubi = new UbigeoBE();
            ubi.CodProv = Sel_Prov;
            ubi.CodDpto = Sel_Dpto;

            JsonResult result = new JsonResult();
            var vDistritos = generalService.ListarUbigeo(ubi, 3);



            result.Data = vDistritos.ToList();
            result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;

            //create1(ubi);
            return result;

        }

        public ActionResult Select(int id)
        {
            var cache = new CacheProvider();

            UbigeoBE ubigeo = new UbigeoBE();

            UsuariosBE user = (UsuariosBE)Session["user"];

            Response_Proveedor response = new Response_Proveedor();

            response = service.ProveedorById(new ProveedorBE() { IDProveedor = id }, user);

            var proveedor = response.GetProveedor;
            var Listpersonal = response.listPersonalBE;
            //if (proveedor != null ){
            ubigeo.CodDpto = proveedor.CodUbigeo.Substring(0, 2);
            ubigeo.CodProv = proveedor.CodUbigeo.Substring(2, 2);
            ubigeo.CodDist = proveedor.CodUbigeo.Substring(4, 2);



            //para listado de personal
            var model = new ProveedorModel(proveedor, ubigeo, ListaProveedor(), new PersonalBE());
            model.Action = "search";
            model.ToolBar = new ToolBarModel();


            model.Personales = new List<PersonalModel>();
            foreach (var per in Listpersonal.ToList())
            {
                model.Personales.Add(new PersonalModel(per));

            }


            model.Provincia = new SelectList(generalService.ListarUbigeo(ubigeo, 2), "CodProv", "DescUbigeo", model.Provincia);
            model.Distrito = new SelectList(generalService.ListarUbigeo(ubigeo, 3), "CodDist", "DescUbigeo", model.Distrito);
            model.Departamento = new SelectList(generalService.ListarUbigeo(new UbigeoBE(), 1), "CodDpto", "DescUbigeo", model.Departamento);




            cache.Set(model.ID.Value.ToString(), model);




            return View(@"~/Views/proveedor/Edit.aspx", model);
            //}


            //return AjaxResultSuccess(string.Format("No se encontró sede :{0} ", id));

        }



        public ActionResult Edit(int ruc)
        {
            var cache = new CacheProvider();

            UbigeoBE ubigeo = new UbigeoBE();
            UsuariosBE user = (UsuariosBE)Session["user"];

            Response_Proveedor response = new Response_Proveedor();

            response = service.ProveedorByRuc(new ProveedorBE() { RucProv = ruc }, user);

            var proveedor = response.GetProveedor;
            var Listpersonal = response.listPersonalBE;

            if (proveedor != null)
            {
                ubigeo.CodDpto = proveedor.CodUbigeo.Substring(0, 2);
                ubigeo.CodProv = proveedor.CodUbigeo.Substring(2, 2);
                ubigeo.CodDist = proveedor.CodUbigeo.Substring(4, 2);



                //para listado de personal
                var model = new ProveedorModel(proveedor, ubigeo, ListaProveedor(), new PersonalBE());
                model.Action = "edit";
                model.ToolBar = new ToolBarModel();


                model.Personales = new List<PersonalModel>();
                foreach (var per in Listpersonal)
                {
                    model.Personales.Add(new PersonalModel(per));

                }


                model.Provincia = new SelectList(generalService.ListarUbigeo(ubigeo, 2), "CodProv", "DescUbigeo", model.Provincia);
                model.Distrito = new SelectList(generalService.ListarUbigeo(ubigeo, 3), "CodDist", "DescUbigeo", model.Distrito);
                model.Departamento = new SelectList(generalService.ListarUbigeo(new UbigeoBE(), 1), "CodDpto", "DescUbigeo", model.Departamento);




                cache.Set(model.ID.Value.ToString(), model);




                return View(@"~/Views/proveedor/Edit.aspx", model);
            }

            //var  model1 = new ProveedorModel(proveedor, ubigeo, ListaProveedor(), new PersonalBE());
            //model1.Action = "edit";
            //model1.ToolBar = new ToolBarModel();


            return AjaxResultSuccess(string.Format("No se encontró proveedor :{0} ", ruc));

        }










        public JsonResult BuscarProveedor(int cad)
        {


            var list = service.BuscarProveedor(new ProveedorBE() { RucProv = cad });

            JsonResult result = new JsonResult();
            result.Data = list.ToList();

            result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;

            return result;

        }


        public JsonResult AddOrEditPersonal(Guid id, Guid personalGuid, string action)
        {
            try
            {
                var personal = new PersonalController().GetPersonalModel(personalGuid);
                var model = GetProveedorModel(id);
                if (action == "create")
                {
                    personal.Personal.IDPersonal = 0;
                    model.Personales.Add(personal);
                }
                else if (action == "edit")
                {
                    var personalToEdit = model.Personales.FirstOrDefault(x => x.ID == personalGuid);
                    personalToEdit = personal;
                }

                return AjaxResultSuccessNoParam();
            }
            catch (Exception ex)
            {
                return AjaxResultError(ex.Message);
            }
        }

        public ViewResult DeletePersonal(Guid id, Guid personalGuid)
        {
            var model = GetProveedorModel(id);
            var personal = model.Personales.FirstOrDefault(x => x.ID == personalGuid);
            model.Personales.Remove(personal);

            if (model.Action == "edit" && personal.Personal.IDPersonal > 0)
            {
                model.toDelete.Add(personal.Personal.IDPersonal);
            }

            return View(@"~/Views/Proveedor/ListaPersonal.ascx", model);
        }



        public ViewResult LoadAddOrEditPersonal(Guid id, Guid? personalGuid)
        {
            var cache = new CacheProvider();
            PersonalModel personal = null;
            //personal = new PersonalModel(new PersonalBE());
            if (!personalGuid.HasValue)
            {
                personal = new PersonalModel(new PersonalBE());
                personal.Action = "create";
                cache.Set(personal.ID.Value.ToString(), personal);
            }
            else
            {
                var proveedorModel = GetProveedorModel(id);
                personal = proveedorModel.Personales.FirstOrDefault(x => x.ID == personalGuid.Value);
                personal.Action = "edit";
                if (personal.Personal.IDPersonal.HasValue)
                {
                    cache.Set(personalGuid.Value.ToString(), personal);
                }

            }
            return View(@"~/Views/Personal/AddOrEdit.ascx", personal);
        }









        public ProveedorModel GetProveedorModel(Guid id)
        {
            var cache = new CacheProvider();

            string key = id.ToString();
            var existingModel = cache.Get(key);
            if (existingModel == null)
            {
                existingModel = new ProveedorModel();
                cache.Set(key, existingModel);
            }
            return (ProveedorModel)existingModel;
        }

        public ActionResult UpdateField(string fieldName, string fieldValue, Guid id, string setterFormatOptions)
        {
            ProveedorModel model = GetProveedorModel(id);
            SetterFormatOptions setterFormatOptionsEnum = SetterFormatOptionsHelper.Parse(setterFormatOptions);
            List<KeyValuePair<string, string>> validationList = new List<KeyValuePair<string, string>>();

            var setter = new PropertySetter<ProveedorModel>.SetterOptions();
            setter.objectToSet = model;
            setter.property = fieldName;
            setter.val = fieldValue;
            setter.SetterFormatOptions = setterFormatOptionsEnum;
            setter.validationList = validationList;

            object valueWasSet = PropertySetter<ProveedorModel>.SetFinalObject(setter);

            validationList.AddRange(new ProveedorModelValidator().Validate(model));

            return Json
                (new
                {
                    result = true,
                    PropertyValidationList = validationList
                }
                );
        }

        public ActionResult GetValidation(Guid id)
        {
            ProveedorModel model = GetProveedorModel(id);
            List<KeyValuePair<string, string>> validationList = new List<KeyValuePair<string, string>>();
            List<KeyValuePair<string, string>> propertyChangeList = new List<KeyValuePair<string, string>>();

            validationList.AddRange(new ProveedorModelValidator().Validate(model));

            return Json(new
            {
                PropertyValidationList = validationList,
                PropertyVisibilityList = propertyChangeList
            });
        }

        public ViewResult GetListaPersonal(Guid id)
        {
            ProveedorModel model = GetProveedorModel(id);
            return View(@"~/Views/Proveedor/ListaPersonal.ascx", model);
        }



    }
}
